package com.zzyl.intercept;

import cn.hutool.core.map.MapUtil;
import com.zzyl.constant.Constants;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.utils.*;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
/**
 * 前端用户的拦截
 * */
@Slf4j
@Component
public class MemberInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtTokenManagerProperties jwtTokenManagerProperties;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        if (token == null) {
            response.setStatus(HttpStatus.UNAUTHORIZED);
            return false;
        }
        try {
            Claims claims = JwtUtil.parseJWT(jwtTokenManagerProperties.getBase64EncodedSecretKey(), token);
            Long userId = claims.get(Constants.JWT_USERID, Long.class);
            String userName = claims.get(Constants.JWT_USERNAME, String.class);
            log.info("token中解析userId:{} username:{}", userId, userName);
            // 鉴权的时候使用label字段  不再使用interceptor
           /* Set<String> urlList = stringRedisTemplate.opsForSet().members(UserCacheConstant.USER_RESOURCE + userId);
            if (CollectionUtil.isEmpty(urlList)) {
                log.info("redis中读取的url列表为空");
                response.setStatus(HttpStatus.FORBIDDEN);
                return false;
            }
            String requestMethod = request.getMethod().toUpperCase();
            String requestUrl = request.getRequestURI();
            // 使用antPathMatcher来进行路径的模糊匹配
            boolean hasRequestPermission = false;
            for (String urlInRedis : urlList) {
                if (antPathMatcher.match(urlInRedis, requestMethod + requestUrl)) {
                    hasRequestPermission = true;
                    break;
                }
            }
            if (!hasRequestPermission) {
                // 说明没有访问权限
                log.info("没有访问权限");
                response.setStatus(HttpStatus.FORBIDDEN);
                return false;
            }*/
            UserThreadLocal.setSubject(""+userId);
            return true;
        } catch (Exception e) {
            log.info("token解析失败");
            response.setStatus(HttpStatus.UNAUTHORIZED);
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                Exception ex) throws Exception {

    }
}


/*
    @Autowired
    private JwtTokenManagerProperties jwtTokenManagerProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //判断当前请求是否是handler()
        if(!(handler instanceof HandlerMethod)){
            return true;
        }

        //获取token
        String token = request.getHeader(Constants.USER_TOKEN);
        if(StringUtils.isEmpty(token)){
            throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);
        }
        //解析token
        Map<String, Object> claims = JwtUtil.parseJWT(jwtTokenManagerProperties.getBase64EncodedSecretKey(), token);
        if(ObjectUtil.isEmpty(claims)){
            throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);
        }
        //Long userId = (Long) claims.get(Constants.JWT_USERID);
        Long userId = MapUtil.get(claims, Constants.JWT_USERID, Long.class);
        if(ObjectUtil.isEmpty(userId)){
            throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);
        }
        //把数据存储到线程中
        UserThreadLocal.set(userId);

        return true;

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}*/
